<template>
  <view class="order-detail">
    <scroll-view class="detail-scroll" scroll-y>
      <view class="detail-content">
        <!-- 订单状态卡片 -->
        <view class="status-card">
          <view class="status-header">
            <uni-icons type="checkmarkempty" size="32" :color="getStatusColor(orderData.status)" />
            <text class="status-text">{{ getOrderStatusText(orderData.status) }}</text>
          </view>
          <text class="status-desc">{{ getStatusDescription(orderData.status) }}</text>
        </view>

        <!-- 订单基本信息 -->
        <view class="info-section">
          <view class="section-header">
            <text class="section-title">订单信息</text>
          </view>
          <view class="info-card">
            <view class="info-list">
              <view class="info-item">
                <text class="info-label">订单号</text>
                <text class="info-value">{{ orderData.order_no }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">活动名称</text>
                <text class="info-value">{{ orderData.activity_name }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">用户名</text>
                <text class="info-value">{{ orderData.username }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">购买数量</text>
                <text class="info-value">{{ orderData.quantity }}件</text>
              </view>
              <view class="info-item">
                <text class="info-label">订单金额</text>
                <text class="info-value price">¥{{ formatPrice(orderData.amount) }}</text>
              </view>
              <view class="info-item" v-if="orderData.paid_at">
                <text class="info-label">支付时间</text>
                <text class="info-value">{{ formatDateTime(orderData.paid_at) }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">下单时间</text>
                <text class="info-value">{{ formatDateTime(orderData.created_at) }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 团购信息 -->
        <view class="info-section" v-if="orderData.group_status !== undefined">
          <view class="section-header">
            <text class="section-title">团购信息</text>
          </view>
          <view class="info-card">
            <view class="group-status-info">
              <view class="group-status-badge">
                <uni-tag 
                  :text="getGroupStatusText(orderData.group_status)" 
                  :type="getGroupStatusType(orderData.group_status)"
                />
              </view>
              <text class="group-desc">{{ getGroupDescription(orderData.group_status) }}</text>
            </view>
          </view>
        </view>

        <!-- 收货信息 -->
        <view class="info-section" v-if="orderData.address">
          <view class="section-header">
            <text class="section-title">收货信息</text>
          </view>
          <view class="info-card">
            <view class="address-info">
              <uni-icons type="location" size="16" color="#666" />
              <text class="address-text">{{ orderData.address }}</text>
            </view>
          </view>
        </view>

        <!-- 备注信息 -->
        <view class="info-section" v-if="orderData.remark">
          <view class="section-header">
            <text class="section-title">备注信息</text>
          </view>
          <view class="info-card">
            <text class="remark-text">{{ orderData.remark }}</text>
          </view>
        </view>

        <!-- 操作记录 -->
        <view class="info-section">
          <view class="section-header">
            <text class="section-title">操作记录</text>
          </view>
          <view class="timeline-card">
            <view class="timeline-list">
              <view class="timeline-item" v-for="(record, index) in operationRecords" :key="index">
                <view class="timeline-dot" :class="{ active: index === 0 }"></view>
                <view class="timeline-content">
                  <text class="timeline-title">{{ record.title }}</text>
                  <text class="timeline-time">{{ record.time }}</text>
                  <text class="timeline-desc" v-if="record.desc">{{ record.desc }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions" v-if="canOperate">
      <button 
        class="action-btn secondary" 
        v-if="orderData.status === 0"
        @click="cancelOrder"
      >
        取消订单
      </button>
      <button 
        class="action-btn primary" 
        v-if="orderData.status === 1"
        @click="completeOrder"
      >
        完成订单
      </button>
      <button 
        class="action-btn" 
        @click="contactUser"
      >
        联系用户
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { orderApi } from '@/api/groupbuy';
import type { Order } from '@/types/groupbuy';

// 数据
const orderData = ref<Order>({} as Order);
const orderId = ref<number>(0);
const loading = ref(false);

// 操作记录
const operationRecords = ref([
  {
    title: '订单创建',
    time: '',
    desc: '用户下单成功'
  }
]);

// 是否可以操作
const canOperate = computed(() => {
  return orderData.value.status === 0 || orderData.value.status === 1;
});

// 格式化价格
const formatPrice = (price: number) => {
  return (price / 100).toFixed(2);
};

// 格式化日期时间
const formatDateTime = (timestamp: number) => {
  const date = new Date(timestamp * 1000);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  switch (status) {
    case 0: return '待支付';
    case 1: return '已支付';
    case 2: return '已完成';
    case 3: return '已取消';
    default: return '未知状态';
  }
};

// 获取状态颜色
const getStatusColor = (status: number) => {
  switch (status) {
    case 0: return '#FA8C16';
    case 1: return '#52C41A';
    case 2: return '#1890FF';
    case 3: return '#FF4D4F';
    default: return '#999';
  }
};

// 获取状态描述
const getStatusDescription = (status: number) => {
  switch (status) {
    case 0: return '等待用户完成支付';
    case 1: return '用户已完成支付，等待处理';
    case 2: return '订单已完成处理';
    case 3: return '订单已被取消';
    default: return '';
  }
};

// 获取团购状态文本
const getGroupStatusText = (groupStatus: number) => {
  switch (groupStatus) {
    case 0: return '拼团中';
    case 1: return '拼团成功';
    case 2: return '拼团失败';
    default: return '未知';
  }
};

// 获取团购状态类型
const getGroupStatusType = (groupStatus: number) => {
  switch (groupStatus) {
    case 0: return 'warning';
    case 1: return 'success';
    case 2: return 'error';
    default: return 'default';
  }
};

// 获取团购描述
const getGroupDescription = (groupStatus: number) => {
  switch (groupStatus) {
    case 0: return '正在等待更多用户参与拼团';
    case 1: return '拼团人数已满足要求，拼团成功';
    case 2: return '拼团时间已结束，人数不足拼团失败';
    default: return '';
  }
};

// 生成操作记录
const generateOperationRecords = (order: Order) => {
  const records = [
    {
      title: '订单创建',
      time: formatDateTime(order.created_at),
      desc: '用户下单成功'
    }
  ];

  if (order.paid_at) {
    records.push({
      title: '支付完成',
      time: formatDateTime(order.paid_at),
      desc: '用户完成支付'
    });
  }

  if (order.status === 2) {
    records.push({
      title: '订单完成',
      time: formatDateTime(order.created_at), // 这里应该是完成时间，暂时用创建时间
      desc: '订单处理完成'
    });
  }

  if (order.status === 3) {
    records.push({
      title: '订单取消',
      time: formatDateTime(order.created_at), // 这里应该是取消时间，暂时用创建时间
      desc: '订单已被取消'
    });
  }

  operationRecords.value = records.reverse(); // 最新的在前面
};

// 加载订单详情
const loadOrderDetail = async () => {
  if (!orderId.value) return;
  
  try {
    loading.value = true;
    const res = await orderApi.getDetail(orderId.value);
    if (res.success) {
      orderData.value = res.data;
      generateOperationRecords(res.data);
    } else {
      uni.showToast({
        title: res.message || '加载失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('加载订单详情失败:', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    });
  } finally {
    loading.value = false;
  }
};

// 取消订单
const cancelOrder = () => {
  uni.showModal({
    title: '取消订单',
    content: '确定要取消此订单吗？取消后无法恢复。',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await orderApi.updateStatus(orderId.value, 3);
          if (result.success) {
            uni.showToast({
              title: '取消成功',
              icon: 'success',
            });
            loadOrderDetail();
          } else {
            uni.showToast({
              title: result.message || '取消失败',
              icon: 'none',
            });
          }
        } catch (error) {
          uni.showToast({
            title: '取消失败',
            icon: 'none',
          });
        }
      }
    }
  });
};

// 完成订单
const completeOrder = () => {
  uni.showModal({
    title: '完成订单',
    content: '确定要完成此订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await orderApi.updateStatus(orderId.value, 2);
          if (result.success) {
            uni.showToast({
              title: '完成成功',
              icon: 'success',
            });
            loadOrderDetail();
          } else {
            uni.showToast({
              title: result.message || '操作失败',
              icon: 'none',
            });
          }
        } catch (error) {
          uni.showToast({
            title: '操作失败',
            icon: 'none',
          });
        }
      }
    }
  });
};

// 联系用户
const contactUser = () => {
  uni.showActionSheet({
    itemList: ['拨打电话', '发送短信'],
    success: (res) => {
      if (res.tapIndex === 0) {
        // 拨打电话
        uni.showToast({
          title: '功能开发中',
          icon: 'none',
        });
      } else if (res.tapIndex === 1) {
        // 发送短信
        uni.showToast({
          title: '功能开发中',
          icon: 'none',
        });
      }
    }
  });
};

// 页面加载
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = (currentPage as any).options;
  
  if (options.id) {
    orderId.value = parseInt(options.id);
    loadOrderDetail();
  }
});
</script>

<style lang="scss" scoped>
.order-detail {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.detail-scroll {
  flex: 1;
}

.detail-content {
  padding: 24rpx 32rpx 120rpx;
}

.status-card {
  background: linear-gradient(135deg, #1890FF 0%, #40A9FF 100%);
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
  color: #fff;
  
  .status-header {
    display: flex;
    align-items: center;
    gap: 16rpx;
    margin-bottom: 12rpx;
    
    .status-text {
      font-size: 32rpx;
      font-weight: 600;
    }
  }
  
  .status-desc {
    font-size: 26rpx;
    opacity: 0.9;
  }
}

.info-section {
  margin-bottom: 32rpx;
  
  .section-header {
    margin-bottom: 16rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
}

.info-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .info-list {
    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 24rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .info-label {
        width: 160rpx;
        font-size: 28rpx;
        color: #666;
        flex-shrink: 0;
      }
      
      .info-value {
        flex: 1;
        font-size: 28rpx;
        color: #333;
        
        &.price {
          font-weight: 600;
          color: #FF4D4F;
        }
      }
    }
  }
  
  .group-status-info {
    display: flex;
    align-items: center;
    gap: 16rpx;
    
    .group-desc {
      font-size: 26rpx;
      color: #666;
    }
  }
  
  .address-info {
    display: flex;
    align-items: flex-start;
    gap: 12rpx;
    
    .address-text {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      line-height: 1.5;
    }
  }
  
  .remark-text {
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
  }
}

.timeline-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .timeline-list {
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      left: 16rpx;
      top: 32rpx;
      bottom: 32rpx;
      width: 2rpx;
      background: #f0f0f0;
    }
    
    .timeline-item {
      position: relative;
      padding-left: 64rpx;
      margin-bottom: 32rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .timeline-dot {
        position: absolute;
        left: 8rpx;
        top: 8rpx;
        width: 16rpx;
        height: 16rpx;
        border-radius: 50%;
        background: #f0f0f0;
        border: 2rpx solid #fff;
        
        &.active {
          background: #1890FF;
        }
      }
      
      .timeline-content {
        .timeline-title {
          font-size: 28rpx;
          font-weight: 600;
          color: #333;
          display: block;
          margin-bottom: 8rpx;
        }
        
        .timeline-time {
          font-size: 24rpx;
          color: #999;
          display: block;
          margin-bottom: 8rpx;
        }
        
        .timeline-desc {
          font-size: 26rpx;
          color: #666;
          display: block;
        }
      }
    }
  }
}

.bottom-actions {
  display: flex;
  padding: 24rpx 32rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  gap: 24rpx;
  
  .action-btn {
    flex: 1;
    height: 88rpx;
    border-radius: 12rpx;
    font-size: 32rpx;
    border: none;
    background: #1890FF;
    color: #fff;
    
    &.secondary {
      background: #f5f5f5;
      color: #666;
    }
    
    &.primary {
      background: #52C41A;
    }
  }
}
</style>